Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | ACADEMIC RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * PROJECT METADATA8 * -----------------------------------------------------------------------------9 * Project : UQO Éval10 * File : src/app/api/metre/versions/[id]/route.ts11 * Module : app12 * Repository : https://git.spboucher.ai/uqo-eval13 * Project Website : https://www.uqo-eval.app14 * Created : 2026-10-2815 * Last Modified : 2026-10-2816 *17 * =============================================================================18 * SOFTWARE MAINTAINER & AFFILIATION19 * =============================================================================20 *21 * Maintainer : Simon-Pierre Boucher22 * Position : Professor of Finance23 * Institution : Université du Québec en Outaouais (UQO)24 * Department : Département des sciences administratives25 * Website : https://spboucher.ai26 * Git : https://git.spboucher.ai27 *28 * Research Contact : research@spboucher.ai29 * Direct Contact : simon@spboucher.ai30 * Security/Admin : admin@spboucher.ai31 *32 * The affiliation is descriptive. It is not an institutional endorsement,33 * a license grant or a determination of ownership.34 *35 * =============================================================================36 * COPYRIGHT, AUTHORSHIP & DATA37 * =============================================================================38 *39 * Copyright (c) the author(s) of this work.40 * Ownership is not asserted by this notice; see the repository records.41 *42 * This header identifies the maintainer of the software. Scientific43 * authorship of any associated paper is stated in the paper itself and44 * is not changed by this notice. Datasets and third-party materials45 * remain the property of their respective owners and licensors.46 *47 * This file is governed by the applicable project license, copyright48 * notices, institutional agreements and relevant law.49 *50 * =============================================================================51 * LICENSE & MAINTENANCE52 * =============================================================================53 *54 * License : None specified (no license file in this repository)55 * Classification : Public56 *57 * =============================================================================58 * END OF SP BOUCHER SOURCE HEADER59 * =============================================================================60 */6162// UQO Éval — Métré : une révision immuable — JSON, rapport PDF (?format=pdf&lang=fr|en), CSV, XLSX.63import { NextRequest, NextResponse } from "next/server";64import { randomUUID } from "crypto";65import { HttpError, handle, requireProject, requireUser } from "@/lib/metre/auth";66import { getVersion, listValuationCases } from "@/lib/metre/estimates";67import { getProject } from "@/lib/metre/projects";68import { listMeasurements } from "@/lib/metre/plans";69import { buildMetreReport } from "@/lib/metre/report";70import { versionToCsv, versionToXlsx } from "@/lib/metre/exports";7172export const runtime = "nodejs";73export const maxDuration = 60;7475const slug = (s: string) => s.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "projet";7677export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {78 return handle(async () => {79 const { id } = await params; const ctx = requireUser(req, { limit: { key: "report", max: 60, windowMs: 60_000 } });80 const v = getVersion(ctx.db, id); if (!v) throw new HttpError(404, "Révision introuvable.");81 requireProject(ctx, v.projectId, "read");82 const format = req.nextUrl.searchParams.get("format") ?? "json";83 const lang = req.nextUrl.searchParams.get("lang") === "en" ? "en" : "fr";84 if (format === "json") return NextResponse.json({ version: v });85 const p = getProject(ctx.db, v.projectId)!;86 const ms = listMeasurements(ctx.db, v.projectId);87 const base = `uqo-eval-metre-${slug(p.name)}-r${v.number}`;88 const log = (kind: string, bytes: number) => ctx.db.prepare("INSERT INTO metre_report_jobs(id,project_id,estimate_version_id,kind,lang,requested_by,bytes) VALUES(?,?,?,?,?,?,?)").run(randomUUID(), v.projectId, v.id, kind, lang, ctx.user.id, bytes);89 if (format === "csv") { const csv = versionToCsv(v, lang); log("csv", csv.length); return new NextResponse(csv, { headers: { "Content-Type": "text/csv; charset=utf-8", "Content-Disposition": `attachment; filename="${base}.csv"`, "Cache-Control": "private, no-store" } }); }90 if (format === "xlsx") { const buf = await versionToXlsx(p, v, ms, lang); log("xlsx", buf.length); return new NextResponse(new Uint8Array(buf), { headers: { "Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Content-Disposition": `attachment; filename="${base}.xlsx"`, "Cache-Control": "private, no-store" } }); }91 if (format === "pdf") {92 const vcId = req.nextUrl.searchParams.get("valuation");93 const valuation = listValuationCases(ctx.db, v.projectId).find((c) => (vcId ? c.id === vcId : c.estimateVersionId === v.id)) ?? null;94 const owner = (ctx.db.prepare("SELECT display_name n FROM metre_users WHERE id=?").get(p.ownerId) as { n: string } | undefined)?.n ?? "—";95 const pdf = await buildMetreReport({ project: p, version: v, measurements: ms, valuation, lang, ownerName: owner, generatedBy: ctx.user.role });96 log("pdf", pdf.length);97 return new NextResponse(new Uint8Array(pdf), { headers: { "Content-Type": "application/pdf", "Content-Disposition": `attachment; filename="${base}-${lang}.pdf"`, "Cache-Control": "private, no-store" } });98 }99 throw new HttpError(400, "format : json | pdf | csv | xlsx");100 });101}102